//
//  XMMessageSendView.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/4.
//

#import "XMMessageSendView.h"
//#import "XMChatVoiceRecorder.h"
#import "XMChatCreatVoice.h"
#import "XMChatImgSend.h"

@interface XMMessageSendView ()<UITextFieldDelegate, XMChatCreatVoiceDelegate>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UITextField *messageTextField;
@property (nonatomic, strong) UIButton *voiceBtn;
@property (nonatomic, strong) UIButton *addImgBtn;

@property (nonatomic, strong) XMChatCreatVoice *recorder;
@property (nonatomic, strong) NSDate *recordStartTime;

@property (nonatomic, strong) UIButton *voiceInputBtn;

@end

@implementation XMMessageSendView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    self.backgroundColor = kColorHEX(0xffffff);
//    [self addSubview:self.voiceBtn];
    UIView *fieldBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height - kBottomLayout)];
    [self addSubview:fieldBgView];
    [fieldBgView addSubview:self.messageTextField];
    [fieldBgView addSubview:self.voiceBtn];
    [fieldBgView addSubview:self.voiceInputBtn];
    [fieldBgView addSubview:self.addImgBtn];
//    [self addSubview:self.messageTextField];
//    [self addSubview:self.voiceInputBtn];
//    [self addSubview:self.addImgBtn];
    _voiceInputBtn.hidden = YES;
}

- (void)voiceSelectAction:(UIButton *)button {
    button.selected = !button.selected;
    _messageTextField.hidden = button.selected;
    _voiceInputBtn.hidden = !button.selected;
}

- (void)longPress:(UILongPressGestureRecognizer *)longPress {
    NSLog(@"长按");
    if (longPress.state == UIGestureRecognizerStateBegan) {
        NSLog(@"长按开始");
        [self.recorder record];
    }
    else if (longPress.state == UIGestureRecognizerStateChanged) {
        NSLog(@"长按中");
    }
    else if (longPress.state == UIGestureRecognizerStateEnded) {
        NSLog(@"长按结束");
//        NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:_recordStartTime];
//        if (interval < 1) {
            [self.recorder stop];
//        } else if (interval > 60) {
//            [self.recorder cancel];
//        } else {
//            [self.recorder stop];
//            NSString *path = self.recorder.recordedFilePath;
//            if (path) {
//                NSLog(@"创建语音成功%@", path);
//                self.voiceSendBlock ? self.voiceSendBlock(path) : nil;
//            }
//        }
    }
}

- (void)disMiss {
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.y = kScreentHeight - weakSelf.height;
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length == 0) {
        [MBProgressHUD showError:@"消息不能为空 "];
        return NO;
    }
    [self endEditing:YES];
    self.messageSendBlock ? self.messageSendBlock(textField.text) : nil;
    return YES;
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.y = kScreentHeight - keyboardRect.size.height - KScaleWidth(80.0);
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [self disMiss];
}

- (void)sendSuccess {
    _messageTextField.text = @"";
}

- (void)addImgAction:(UIButton *)button {
    button.selected = !button.selected;
    self.fucSelectBlock ? self.fucSelectBlock(button.selected) : nil;
//    XMWeakSelf;
//    if (button.selected) {
//        [UIView animateWithDuration:.3 animations:^{
//            weakSelf.y = kScreentHeight - weakSelf.messageTextField.superview.height - weakSelf.funcBgView.height;
//            weakSelf.funcBgView.y = kScreentHeight - weakSelf.funcBgView.height;
//        }];
//    }
//    else {
//        [UIView animateWithDuration:.3 animations:^{
//            weakSelf.y = kScreentHeight - weakSelf.height;
//            weakSelf.funcBgView.y = kScreentHeight;
//        }];
//    }
}

#pragma mark - VoiceDelegate
//- (void)audioRecorder:(XMChatVoiceRecorder *)recorder
//   didCheckPermission:(BOOL)isGranted
//          isFirstTime:(BOOL)isFirstTime {
//    if (isFirstTime) {
//        if (!isGranted) {
//            [MBProgressHUD showError:@"无权限"];
//        }
//        return;
//    }
//    _recordStartTime = [NSDate date];
//}

/// Power value can be used to simulate the animation of mic changes when speaking.
//- (void)audioRecorder:(XMChatVoiceRecorder *)recorder
//      didPowerChanged:(float)power {
//
//}

//- (void)audioRecorder:(XMChatVoiceRecorder *)recorder
// didRecordTimeChanged:(NSTimeInterval)time {
//
//}

- (void)creatVoiceSuccess:(NSString *)filePathStr {
    if (filePathStr) {
        NSLog(@"创建语音成功%@", filePathStr);
        self.voiceSendBlock ? self.voiceSendBlock(filePathStr) : nil;
    }
}

#pragma mark - Init

- (UIButton *)voiceBtn {
    if (!_voiceBtn) {
        _voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(KScaleWidth(10.0), KScaleWidth(17.0), KScaleWidth(38.0), KScaleWidth(38.0)) image:@"chat_voice_icon" selectImg:@"chat_keyboard_icon"];
        [_voiceBtn addTarget:self action:@selector(voiceSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceBtn;
}

- (UITextField *)messageTextField {
    if (!_messageTextField) {
        _messageTextField = [[UITextField alloc] initWithFrame:CGRectMake(KScaleWidth(53.0), KScaleWidth(17.0), self.width - KScaleWidth(53.0) - KScaleWidth(96.0), KScaleWidth(38.0))];
        _messageTextField.font = KFontSize(15.0);
        _messageTextField.placeholder = @"发送消息";
        _messageTextField.backgroundColor = kColorHEX(0xF1F1F1);
        [_messageTextField setCornerRadius:KScaleWidth(5.0)];
        _messageTextField.returnKeyType = UIReturnKeySend;
        _messageTextField.delegate = self;
        
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScaleWidth(13.0), _messageTextField.height)];
        _messageTextField.leftView = leftView;
        _messageTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _messageTextField;
}

- (UIButton *)voiceInputBtn {
    if (!_voiceInputBtn) {
        _voiceInputBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(15.0) frame:self.messageTextField.frame title:@"按住 说话" titleColor:kColorHEX(0x333333)];
        [_voiceInputBtn setBackgroundImage:[UIImage imageWithColor:kColorHEX(0xf0f0f0)] forState:UIControlStateHighlighted];
        [_voiceInputBtn setBackgroundImage:[UIImage imageWithColor:kColorHEX(0xF1F1F1)] forState:UIControlStateNormal];
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        longPress.minimumPressDuration = 1;
        [_voiceInputBtn addGestureRecognizer:longPress];
    }
    return _voiceInputBtn;
}

- (XMChatCreatVoice *)recorder {
    if (!_recorder) {
        _recorder = [[XMChatCreatVoice alloc] init];
        _recorder.delegate = self;
    }
    return _recorder;
}

- (UIButton *)addImgBtn {
    if (!_addImgBtn) {
        _addImgBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(self.width - KScaleWidth(10.0) - KScaleWidth(38.0), KScaleWidth(17.0), KScaleWidth(38.0), KScaleWidth(38.0)) image:@"chat_img_add_icon" selectImg:@"chat_img_add_icon"];
        [_addImgBtn addTarget:self action:@selector(addImgAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addImgBtn;
}

//- (XMChatVoiceRecorder *)recorder {
//    if (!_recorder) {
//        _recorder = [[XMChatVoiceRecorder alloc] init];
//    }
//    return _recorder;
//}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
